from typing import List
from common import sent_data, recv_data

from pathlib import Path
import time
import json
import socket
import logging
import threading
import configparser


def sent_file(file: Path, port):
    sub_client = socket.socket()
    sub_client.connect((ip, port))
    logging.info("connect to {}:{}".format(ip, port))

    with file.open("rb") as f:
        while True:
            print(".", end="", flush=True)
            data = f.read(32768)
            if data:
                sub_client.send(data)
            else:
                break
    sub_client.close()
    logging.info("send {}".format("file"))


if __name__ == "__main__":
    logging.basicConfig(filename="log", level=logging.INFO)

    temp_file = Path("temp")

    last_input = {}

    if temp_file.exists():
        with temp_file.open() as f:
            last_input.update(json.load(f))

    print("leave empty to use last value:", last_input)

    ip = input("server ip:") or last_input.get("ip")
    port = input("server port:") or last_input.get("port")
    path = input("file:") or last_input.get("path")

    last_input = {"ip": ip, "port": port, "path": path}
    with temp_file.open("w") as writer:
        writer.write(json.dumps(last_input))

    client = socket.socket()
    client.connect((ip, int(port)))
    logging.info("connect to {}:{}".format(ip, port))

    path = Path(path)
    if path.exists() and path.is_file():
        ...
    else:
        raise ValueError(path)

    size = path.stat().st_size
    logging.info("file {} {} kB".format(path, size))

    data = {"file": path.name, "size": size}
    data = json.dumps(data)

    sent_data(client, data)

    js = recv_data(client)
    js = json.loads(js)

    port = js.get("port")
    logging.info("sent to {}:{}".format(ip, port))

    thread = threading.Thread(target=sent_file, args=(path, port))
    thread.start()
